package cn.dinxian.activiti.service.impl;

import cn.dinxian.activiti.domain.WorkflowLeave;
import cn.dinxian.activiti.mapper.WorkflowLeaveMapper;
import cn.dinxian.activiti.service.IWorkflowLeaveService;
import cn.dinxian.entity.CommonResult;
import cn.dinxian.entity.MyProcessInstance;
import cn.dinxian.api.RuntimeService;
import cn.dinxian.api.TaskService;


import java.util.HashMap;
import java.util.List;

import java.util.Map;
import java.util.stream.Collectors;


import cn.dinxian.common.utils.DateUtils;
import cn.dinxian.common.utils.SecurityUtils;
import cn.dinxian.common.utils.StringUtils;
import cn.dinxian.common.utils.uuid.UUID;
import cn.dinxian.system.service.ISysUserService;
//import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
//import org.activiti.api.process.runtime.ProcessRuntime;
//import org.activiti.engine.RuntimeService;
//import org.activiti.engine.TaskService;
//import org.activiti.engine.runtime.ProcessInstance;
//import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 请假Service业务层处理
 *
 * @author danny
 * @date 2020-10-28
 */
@Service
public class WorkflowLeaveServiceImpl implements IWorkflowLeaveService {

  @Autowired
  private WorkflowLeaveMapper workflowLeaveMapper;
  //@Autowired
  //private ProcessRuntime processRuntime;

  @Autowired
  private RuntimeService runtimeService;

  @Autowired
  private ISysUserService sysUserService;
  @Autowired
  private TaskService taskService;


  /**
   * 查询请假
   *
   * @param id 请假ID
   * @return 请假
   */
  @Override
  public WorkflowLeave selectWorkflowLeaveById(String id) {
    return workflowLeaveMapper.selectWorkflowLeaveById(id);
  }


  /**
   * 查询请假列表
   *
   * @param workflowLeave 请假
   * @return 请假
   */
  @Override
  public List<WorkflowLeave> selectWorkflowLeaveList(WorkflowLeave workflowLeave) {
    return workflowLeaveMapper.selectWorkflowLeaveListByWorkflowLeaveAndDeptId(workflowLeave,
        SecurityUtils.getLoginUser().getUser().getDeptId());
  }

  /**
   * 查询请假列表带任务状态
   *
   * @param workflowLeave 请假
   * @return 请假
   */
  @Override
  public List<WorkflowLeave> selectWorkflowLeaveAndTaskNameList(WorkflowLeave workflowLeave) {
    List<WorkflowLeave> workflowLeaves = workflowLeaveMapper.selectWorkflowLeaveList(workflowLeave);
    List<String> collect = workflowLeaves.parallelStream().map(wl -> wl.getInstanceId())
        .collect(Collectors.toList());
    //if(collect!=null&&!collect.isEmpty()) {
    //    List<Task> tasks = taskService.createTaskQuery().processInstanceIdIn(collect).list();
    //    workflowLeaves.forEach(
    //            wl->{
    //                Task task = tasks.parallelStream().filter(t -> t.getProcessInstanceId().equals(wl.getInstanceId())).findAny().orElse(null);
    //                if (task != null) {
    //                    wl.setTaskName(task.getName());
    //                }
    //            }
    //    );
    //}

    return workflowLeaves;
  }


  /**
   * 新增请假
   *
   * @param workflowLeave 请假
   * @return 结果
   */
  @Override
  public Integer insertWorkflowLeave(WorkflowLeave workflowLeave) {

    String id = UUID.randomUUID().toString();
    workflowLeave.setId(id);
    workflowLeave.setCreateTime(DateUtils.getNowDate());
    String join = StringUtils.join(sysUserService.selectUserNameByPostCodeAndDeptId("se",
        SecurityUtils.getLoginUser().getUser().getDeptId()), ",");
    //ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
    //        .start()
    //        .withProcessDefinitionKey("leave")
    //        .withName(workflowLeave.getTitle())
    //        .withBusinessKey(id)
    //        .withVariable("deptLeader",join)
    //        .build());
    //创建流程实例
    Map<String, Object> varise= new HashMap<>();
    varise.put("deptLeader",join);
    //配置流程的数据
     CommonResult<MyProcessInstance> result = runtimeService.createProcessInstance(
        MyProcessInstance.builder()
            .processDefinitionKey("leave")
            .name(workflowLeave.getTitle())
            .businessKey(id)
            .variable(varise)
            .build()
    );
    //判断是否成功
    if ("200".equals(result.getCode().toString())){
      //插入到历史表中
      MyProcessInstance proc = result.getData();
      workflowLeave.setInstanceId(proc.getId());
      workflowLeave.setState("0");
      workflowLeave.setCreateName(SecurityUtils.getNickName());
      workflowLeave.setCreateBy(SecurityUtils.getUsername());
      workflowLeave.setCreateTime(DateUtils.getNowDate());
      //将数据保存到自己的历史表中
      return workflowLeaveMapper.insertWorkflowLeave(workflowLeave);
    }else
    {
      return null;
    }

    
  }


  /**
   * 修改请假
   *
   * @param workflowLeave 请假
   * @return 结果
   */
  @Override
  public int updateWorkflowLeave(WorkflowLeave workflowLeave) {
    workflowLeave.setUpdateTime(DateUtils.getNowDate());
    return workflowLeaveMapper.updateWorkflowLeave(workflowLeave);
  }


  /**
   * 批量删除请假
   *
   * @param ids 需要删除的请假ID
   * @return 结果
   */
  @Override
  public int deleteWorkflowLeaveByIds(String[] ids) {
    return workflowLeaveMapper.deleteWorkflowLeaveByIds(ids);
  }


  /**
   * 删除请假信息
   *
   * @param id 请假ID
   * @return 结果
   */
  @Override
  public int deleteWorkflowLeaveById(String id) {
    return workflowLeaveMapper.deleteWorkflowLeaveById(id);
  }

  @Override
  public WorkflowLeave selectWorkflowLeaveByInstanceId(String instanceId) {

    return workflowLeaveMapper.selectWorkflowLeaveByInstanceId(instanceId);
  }
}

